package org.jash.demo2205.goods

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import org.jash.demo2205.entity.Goods
import org.jash.demo2205.mvvm.BaseViewModel

class DetailViewModel:BaseViewModel() {
    val goodsLiveData by lazy { MutableLiveData<Goods>() }
    val cartLiveData by lazy { MutableLiveData<String>() }
    fun getDetail(id:Int) {
        viewModelScope.launch {
            try {
                val res = service.getGoodsDetail(id)
                if (res.code == 200) {
                    goodsLiveData.postValue(res.data)
                } else {
                    throw RuntimeException(res.message)
                }
            } catch (e:Exception) {
                failureLiveData.postValue(e)
            }
        }
    }
    fun addToCart(id: Int) {
        viewModelScope.launch {
            try {
                val res = service.addToCart(mapOf("goods_id" to id, "count" to 1))
                if (res.code == 200) {
                    cartLiveData.postValue(res.message)
                } else {
                    throw RuntimeException(res.message)
                }
            } catch (e: Exception) {
                failureLiveData.postValue(e)
            }
        }
    }
}